# ===============================================================================================================
#    PostScan - a plugin for Squeezebox Server 7.5 and greater
#
#    Executes SQL queries or commands against the Squeezebox Server
#	 Database after a music library scan.
#
#    Version 20110506.124207
#
#    Copyright (C) 2010 Gordon Harris
#
#    This program is free software; you can redistribute it and/or
#    modify it under the terms of the GNU General Public License,
#    version 2, which should be included with this software.
#
#	Settings.pm -- adapted from Slim/Plugin/JiveExtras/Settings.pm
#

package Plugins::PostScan::Settings;

use strict;

use base qw(Slim::Web::Settings);

use Slim::Utils::Strings qw(string);

# Global vars
use Plugins::PostScan::Plugin;
use vars qw(%g);
*g = \%Plugins::PostScan::Plugin::g;

#my @prefNames = qw(bGlobalEnabled queries);


sub new {
	my $class = shift;


	$g{log}->is_debug && $g{log}->debug("Settings initialized..");

	$class->SUPER::new;
}


sub name {
	return 'PLUGIN_POSTSCAN';
}

sub page {
	return 'plugins/PostScan/settings/basic.html';
}

sub needsClient {
	return 0;
}

sub getPrefs {
	return $g{prefs};
}

#sub prefs {
#	return ($g{prefs}, @prefNames );
#}

sub logHashElements {

	my @myhash = shift;
	my $num = 0;

	foreach my $item (@myhash) {
		$g{log}->debug("item\[$num\]:");
		while( my ($k, $v) = each %$item ) {
			$g{log}->debug("key: $k, value: " . ( defined($v) ? $v : "undef" ) );
			}
		$num++;
	}
}

sub logArgs {
	my (@args) = @_;
	my $n = 0;

	while (defined($args[$n])) {
		$g{log}->debug("arg[$n] == $args[$n++]");
	}
}

# Handler for the settings html page..

sub handler {
	my ($class, $client, $params, $callback, @args) = @_;
	my $testquery;
	my $bRet;
	my $errmsg;
	my $msgformat;
	my $dispmsg;
	my @sio = Slim::Schema::sourceInformation();

#	$g{log}->is_debug && $g{log}->debug("Settings page handler: \nclass == $class \nparams == $params");
#	$g{log}->is_debug && $g{log}->debug("BEFORE:");
#	$g{log}->is_debug && logHashElements ($params);

	$params->{'query_test_results'} = ' ';
	$params->{'sql_desc'} = sprintf(string('PLUGIN_POSTSCAN_QUERIES_DESC'), $sio[0]);
	
	if ($params->{'saveSettings'}) {

		$g{prefs}->set('bGlobalEnabled', ( $params->{"globalenabled"} eq 'on' ? 1 : 0 ) );

		for my $optname (qw( queries )) {
		
			my @opts;
			my $i = 0;
			my $j = 0;
		
			while (defined $params->{"query$i"}) {

				if ( $params->{"query$i"} ne "" && $params->{"query$i"} ne string('PLUGIN_POSTSCAN_QUERY') ) {

					my $opt = {
						'name'      => $params->{"name$i"},
						'query'     => $params->{"query$i"},
						'validated' => ( $params->{"validated$i"} eq 'on' ? 1 : 0 ),
						'scantype' 	=> ( !$params->{"validated$i"} ? 0 : $params->{"scantype$i"} ),
						#'enabled' 	=> ( $params->{"enabled$i"} eq 'on' ? 1 : 0 ),
					};
        
					if ($params->{"testquery$i"}) {
						$testquery = $opt->{'query'};
						$g{log}->is_debug && $g{log}->debug("Testing Query #$i:\n$testquery");
						($bRet, $errmsg) = Plugins::PostScan::Plugin::performQuery2($testquery);
						$g{log}->is_debug && $g{log}->debug("Query #$i returned $bRet");
						$opt->{'validated'} = $bRet;
						# If not validated, disable the query..
						if (!$bRet) {
							$opt->{'scantype'} = 0;
						}
						#show the test results on the settings page..
						$msgformat = ( $bRet ? string('PLUGIN_POSTSCAN_QUERY_TEST_SUCCESS') : string('PLUGIN_POSTSCAN_QUERY_TEST_FAILURE') . ' ' . $errmsg );
						$dispmsg = sprintf($msgformat, $opt->{'name'});
						$params->{'query_test_results'} = $dispmsg;
					}

					push @opts, $opt;
					
				}
		
		
				$i++;
			}
		
			$g{prefs}->set($optname, \@opts);
		}
		
	}

	_pushSettings($class, $client, $params, $callback, \@args);

	return $class->SUPER::handler($client, $params);
}


sub _pushSettings {
	my ($class, $client, $params, $callback, $args) = @_;
	
	$params->{'globalenabled'} = $g{prefs}->get('bGlobalEnabled');

	for my $optname (qw( queries )) {

		$params->{$optname} = [];

		# Existing saved queries..
		for my $opt (@{$g{prefs}->get($optname)}) {
			#if (!$opt->{'validated'}) {
			#	$opt->{'scantype'} = 0;
			#}
			push @{$params->{$optname}}, $opt;
		}

		# New 'blank' query..
		push @{$params->{$optname}}, {
			'name'		=> string('PLUGIN_POSTSCAN_QUERY_NAME') . (scalar @{$params->{$optname}} + 1),
			'query'		=> string('PLUGIN_POSTSCAN_QUERY'),
			'validated'	=> 0,
			'scantype'	=> 0,
		};
	}

	$callback->($client, $params, $class->SUPER::handler($client, $params), @$args);
}

1;
